package com.kdtech.analyse.outside;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.AnalyseNews;
import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;

/**
 * @author KK
 *
 */
public class CnaTWAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://www.cna.com.tw/[^/]*/[^/]*/[[^/]*].aspx",
		"http://www.cna.com.tw/.*/[0-9]{10,}.aspx",
		"http://www.cna.com.tw/.*/[0-9]{10,}-1.aspx",
		"http://www.cna.com.tw/postwrite/Detail/[0-9]+.aspx",
	};

	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();

		news.setUrl(url);
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		title =doc.select(".news_title").text();
		if (title.contains("|")){
			title=StringUtils.substringBefore(title, "|");
		}
		date=DateUtils.matchDate(doc.select(".update_times p:eq(0)").text());
		author=JSoupUtils.matchAuthor(doc, "来源：");		
		content=doc.select(".article_box").html();
		if (StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select("#textContent"));
		}

		if (!StringUtils.isBlank(content) && content.contains("※你可能還想看：")){
			content=StringUtils.substringBefore(content, "※你可能還想看：");
		}
		if (StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select(".box_0 p"));
		}
		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);

		return news;
	}

	public static void main(String args[]){
		String url="http://www.cna.com.tw/news/firstnews/201610315025-1.aspx";
		String html =CrawlHTML.GetHtml(url);
		System.out.println(html);
		CnaTWAnalyse cnaTWAnalyse=new CnaTWAnalyse();
		System.out.println(cnaTWAnalyse.isDetailPage(url));
		UrlMeta urlMeta=new UrlMeta();
		urlMeta.setHtml(html);
		System.out.println(cnaTWAnalyse.parserHtml(urlMeta));
	}
		

	
}
